<?php


namespace app\admin\controller;


use think\Controller;

class Goods extends Allow
{
    public function index()
    {
        $goods = db("goods")
            ->join('goods_cate','goods.cate_id = goods_cate.cate_id')
            ->order("id desc")
            ->paginate(10);
        $this->assign([
            'goods' => $goods
        ]);
        return view("index");
    }
    public function add()
    {
        $goods_cate = getList(db("goods_cate")->select(),0);
//        dump($goods_cate);
        $this->assign([
            'goods_cate' => $goods_cate
        ]);
        return view("add");
    }
    public function edit()
    {
        $id = input("id");
        $goods = db("goods")->where("id",$id)->find();
//        dump($goods);
        $goods_cate = getList(db("goods_cate")->select(),0);
        $this->assign([
            'goods' => $goods,
            'goods_cate' => $goods_cate
        ]);
        return view("edit");
    }
    public function executeData()
    {
        $id = (int)input("id");
        if(empty($id)){
            $param = request()->param();
            $file = request()->file('image');
            if(empty($file)){
                $param['image'] = null;
            }else{
                $info = $file->move( './static/uploads/');
                $save_name = $info->getSaveName();
                $path = str_replace('\\','/',$save_name);
                $img_path = '/static/uploads/'.$path;
                $param['image'] = $img_path;
            }
            $res = db("goods")->insert($param);
        }else{
            $param = request()->except("id");
            $goods = db("goods")->where("id",$id)->find();
            $param['image'] = editImage($param,$goods,'image');
            $res = db("goods")->where('id',$id)->update($param);
        }
        if(!$res) return ['code' => -1,'msg' => 'error'];
        return ['code' => 200,'msg' => '操作成功'];
    }
    public function delete()
    {
        $id = input("id");
        $del = db("goods")->where("id",$id)->delete();
        if($del){
            return ['code' => 200,'msg' => '删除成功'];
        }else{
            return ['code' => -1,'msg' => '删除失败'];
        }
    }
}